﻿using IceDog.DNF.Program.WebApi2.Models;
using System.Collections.Generic;
using System.Web.Http;
using IceDog.DNF.Program.WebApi2.Repository;

namespace IceDog.DNF.Program.WebApi2.Controllers
{
    /// <summary>
    /// 产品控制器
    /// </summary>
    public class ProductController : ApiController
    {
        private readonly ProductRepository _repository;

        /// <summary>
        /// 每次都会通过一个新的实例来执行，所以repository需要数据库进行持久化
        /// </summary>
        public ProductController()
        {
            _repository = new ProductRepository();
        }

        /// <summary>
        /// 获取所有的产品列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Product> Get()
        {
            return _repository.GetAllProducts();
        }
        /// <summary>
        /// 根据产品编号获取产品
        /// </summary>
        /// <param name="id">产品编号</param>
        /// <returns></returns>
        public IHttpActionResult Get(int id)
        {
            var product = _repository.GetProductById(id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        /// <summary>
        /// 根据产品分类获取产品
        /// </summary>
        /// <param name="category">产品分类</param>
        /// <returns></returns>
        public IHttpActionResult Get(string category)
        {
            var products = _repository.GetProductByCategory(category);
            if (products == null)
            {
                return NotFound();
            }
            return Ok(products);
        }
        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="product">产品对象</param>
        [HttpGet]
        public IHttpActionResult Post(Product product)
        {
            var result = _repository.AddProduct(product);
            return Ok(result);
        }

        /// <summary>
        /// 删除产品
        /// </summary>
        /// <param name="id">产品编号</param>
        /// <returns></returns>
        public IHttpActionResult Delete(int id)
        {
            var result = _repository.RemoveProduct(id);
            return Ok(result);
        }

        /// <summary>
        /// 更新产品
        /// </summary>
        /// <param name="id">产品编号</param>
        /// <param name="product">产品对象</param>
        /// <returns></returns>
        public IHttpActionResult Patch(int id, Product product)
        {
            var result = _repository.UpdateProduct(id, product);
            return Ok(result);
        }
    }
}
